package com.websocket;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

@ServerEndpoint("/websocket")
public class WebSocketMessage {
    /**
     * 存储当前有效的session对象
     */
    private static Queue<Session> sessionSet = new ConcurrentLinkedQueue<Session>();
    @OnMessage
    public void onMessage(String message, Session currentSession) {
        System.out.println("Server say：Received: " + message);
        try {
            final Set<Session> sessions = currentSession.getOpenSessions();//获得又少条连接信息
            System.out.println("检测到连接服务器是对象数量是" + sessions.size());

            //客户端互相发送消息
            for (Session session : sessions) {
                session.getBasicRemote().sendText(message);
            }
            /************启动定时公告**************/
            SystemTimer.getInstance();
            /**************************/
        } catch (IOException e) {
            System.out.println("警告");
        }
    }
    @OnOpen
    public void onOpen(Session currentSession) {
        if(sessionSet.contains(currentSession) == false){
            sessionSet.add(currentSession);
            System.out.println("WebSocketTest.onOpen()================Add=" + sessionSet.size());
        }
        System.out.println("Server say：Client connected");
    }
    @OnClose
    public void onClose(Session currentSession) {
        if(sessionSet.contains(currentSession)){
            sessionSet.remove(currentSession);
        }
        System.out.println("Server say：Connection closed============Close=" + sessionSet.size());
    }
    public static Queue<Session> getSessionSet() {
        return sessionSet;
    }

}